<?php

namespace app\admin\model;

use think\Model;

class ExpressModel extends Model
{
    // 确定链接表名
    protected $name = 'express';


    
    public function getStatusAttr($value){
        $status = ['未揽件', '已揽件'];
        return $status[$value];
    }

    /**
     * 根据搜索条件获取订单列表信息
     * @param $where
     * @param $offset
     * @param $limit
     */
    public function getUsersByWhere($where, $offset, $limit)
    {
        return $this->where($where)->limit($offset, $limit)->order('id desc')->select();
    }

    /**
     * 根据搜索条件获取所有的订单数量
     * @param $where
     */
    public function getAllUsers($where)
    {
        return $this->where($where)->count();
    }


    /**
     * 编辑订单信息
     * @param $param
     */
    public function editUser($param)
    {
        try{
            $result =  $this->save($param, ['id' => $param['id']]);
            return msg(1, url('user/index'), '编辑用户成功');
        }catch(PDOException $e){
            return msg(-2, '', $e->getMessage());
        }
    }


    /**
     * 删除订单
     * @param $id
     */
    public function del($id)
    {
        try{

            $this->where('id', $id)->delete();
            return msg(1, '', '删除订单成功');

        }catch( PDOException $e){
            return msg(-1, '', $e->getMessage());
        }
    }

    // 单件入库
    public function insertOne($param){
        try {
            $this->save($param);
            return msg(0, '', 'ok');
        } catch (\Throwable $th) {
            //throw $th;
            return msg(-1, '', $th->getMessage());
        }
    }

    // 单件出库
    public function outstore($code){
        try {
            $this->where('billcode', $code)->update(['status'=>1]);
            return msg(1, '', 'ok');
        } catch (\Throwable $th) {
            //throw $th;
            return msg(-1, '', $th->getMessage());
        }
    }


    /**
     * 更新订单状态
     * @param array $param
     */
    public function updateStatus($param = [], $uid)
    {
        try{

            $this->where('id', $uid)->update($param);
            return msg(1, '', 'ok');
        }catch (\Exception $e){

            return msg(-1, '', $e->getMessage());
        }
    }
    /**
     * 获取快递公司快件数
     */
    public function getCount($type){
        return $this->where('company_code', $type)->count();
    }
    
    /**
     * 根据时间获取公司快件数
     */
    public function search($time){
        $data = $this->field('company_code, count(id) as sum')
        ->whereTime('create_time', 'between', $time)
        ->group('company_code')->select();
        $info = [];
        $count = 0;
        foreach ($data as $v) {
            $info[$v['company_code']] = $v['sum'];
            $count += $v['sum'];
        }
        $info['total'] = $count;
        return $info;
    }
}
